var SortFormObject=function(){
	var self=this;
	this.searchFilter=$('#search-filter');
	this.main=$('#main');
	/*展示的dom列表结构中的东西start*/
	this.houseSaleListPanel=$('#house-saleList');
	this.resMsg=$('#res-msg');
	this.imageHost=common.imageHost;
	this.flag=true;
	/*dom结构中的东西end*/
	this.typeList=self.searchFilter.children('.type-list');
	this.panel=self.searchFilter.children('.panel');
	this.searchArea=self.searchFilter.children('#search-area');
	this.searchTotalPrice=self.searchFilter.children('#search-total-price');
	this.searchHouseType=self.searchFilter.children('#search-house-type');
	this.searchMoreSort=self.searchFilter.children('#search-more-sort');
	this.myForm=self.searchFilter.children('#myForm');
	this.loadingFail=$('.loading-fail');
	/*区域地铁隐藏域start*/
	this.lineId=$(self.myForm.find('#lineId'));
	this.stationId=$(self.myForm.find('#stationId'));
	this.zoneId3=$(self.myForm.find('#zoneId3'));
	this.zoneId4=$(self.myForm.find('#zoneId4'));
	/*区域地铁隐藏域end*/
	this.mask=$('#mask');
	this.secondList=$('#secondList');
    this.thridList=$('#thridList');
    this.panelCell=$(self.searchArea.find('.panel-cell'));
    this.firstList=$(self.searchArea.find('.area1'));
    this.globalHost=common.globalHost;
    this.lineUrl=self.globalHost+common.getLineList;
	this.zoneUrl=self.globalHost+common.getZoneList;
	this.getRewardListUrl=self.globalHost+common.getRewardHouseList;
    this.zoneList=[];
    this.lineList=[];
	this.token=common.getToken();
	this.sendData={
    	pageNum:1,
        numPerPage:10,
        token:self.token,
        type:'',
        rewardStatus:'1'
    };
    this.sendContent={
    	status:"AVAILABLE",
    	token:self.token,
    	level:3,
    	upZoneId:"402881ff584768bf0158478bc98b0000",
    };
    /*获取地铁模块数据*/
	self.requestInitData({
        url:self.lineUrl,
        sendData:self.sendContent,
        callBack:function(data){
            var data=data['res']['data']['record'];
            var linesList=[];
            var initOli='<li class="chosen">不限</li>';
            linesList.push(initOli);
            data=data.sort(function (a,b) {
                return a["sort"]-b["sort"];
            });
            $.each(data,function (idx, ele) {
                linesList.push('<li data-value="'+ele.id+'">'+ele.lineName+'</li>');
            });
            self.secondList.html(linesList.join(""));
            self.lineList=data;
            /*点击区域或者地铁线*/
			self._pressLineOrArea({dataList:data,selectedType:"subway"});
        }
    });
    /*获取区域模块数据*/
	self.requestInitData({
        url:self.zoneUrl,
        sendData:self.sendContent,
        callBack:function(data){
            var data=data['res']['data']['record'];
            self.zoneList=data;
        }
    });
    /*顶部切换*/
	self.typeListTab();
	self.moreSort({
		targetSelector:self.searchMoreSort
	});
	self.addInputHidden({
		targetSelector:self.searchMoreSort,
		inputHidden:self.myForm.find('#houseSort'),
		typeList:self.typeList
	});
	self.checkBoxes({
		targetSelector:self.searchHouseType,
		inputHidden:self.myForm.find('#houseType'),
		title:"房型"
	});
	self.searchBtn({
		targetSelector:self.searchHouseType,
		inputHidden:self.myForm.find('#houseType'),
		title:"房型"
	});
	self.checkBoxes({
		targetSelector:self.searchTotalPrice,
		inputHidden:self.myForm.find('#housePrice'),
		title:"总价"
	});
	self.searchBtn({
		targetSelector:self.searchTotalPrice,
		inputHidden:self.myForm.find('#housePrice'),
		title:"总价",
		input:self.searchTotalPrice.find('input')
	});
	self.onClickMask({
		targetSelector:self.mask,
	});
	/*阻止蒙版事件冒泡*/
	self.mask.off("touchmove").on("touchmove",function(ev){
		ev.stopPropagation();
		ev.preventDefault();
		return false;
	});
	/*阻止事件冒泡*/
	self.searchTotalPrice.off("touchmove").on("touchmove",function(ev){
		ev.stopPropagation();
		ev.preventDefault();
		return false;
	});
	self.searchHouseType.off("touchmove").on("touchmove",function(ev){
		ev.stopPropagation();
		ev.preventDefault();
		return false;
	});
	self.searchMoreSort.off("touchmove").on("touchmove",function(ev){
		ev.stopPropagation();
		ev.preventDefault();
		return false;
	});
	/*点击区域或地铁*/
    self._pressZoneOrStation();
    self._pressPositionList();
};
SortFormObject.prototype = {
	/*控制隐藏部分的显示隐藏，以及顶部的样式*/
	typeListTab:function(){
		var self=this;
		self.typeList.children('li').off('tap').on('tap',function(e){
			var $this=$(this);
			var index=$this.index();
			var checkCase=$this.hasClass('on');
			!!checkCase?$this.removeClass('on')&&self.panel.eq(index).hide().removeClass('open')&&self.mask.hide():$this.addClass('on').siblings().removeClass('on')&&self.panel.hide().removeClass('open')&&self.panel.eq(index).slideDown(200).addClass('open')&&self.mask.show();
			$this.hasClass('area')?self.main.addClass('active'):"";
			e.preventDefault();
	    	return false;
		})
	},
	/*更多部分功能实现*/
	moreSort:function(options){
		var self=this;
		var $targetSelector=$(options.targetSelector);
		$targetSelector.off('tap','li').on('tap','li',function(e){
			var $this=$(this);
			$this.hasClass('chosen')?$this.removeClass('chosen'):$targetSelector.find('li').removeClass('chosen')&&$this.addClass('chosen');
			e.preventDefault();
			return false;
		})
	},
	/*更多部分添加隐藏域*/
	addInputHidden:function(options){
		var self=this;
		var $targetSelector=$(options.targetSelector);
		var $inputHidden=$(options.inputHidden);
		var $targetBtn=$targetSelector.find('p');
		var $typeList=$(options.typeList);
		var	parentContainer=self.searchFilter;
		$targetBtn.off('tap').on('tap',function(e){
			var chosenBox=$targetSelector.find('.chosen');
			var value=chosenBox.attr('data-value');
			if(!!chosenBox&&chosenBox.length!=0){
				$typeList.find('.on').children('span').html(chosenBox.html()).addClass('selected').end().removeClass('on');
			}else{
				$typeList.find('.on').children('span').html("更多").removeClass('selected').end().removeClass('on');
				value="";
			}
			$inputHidden.val(value);
            self.requestData({url:self.getRewardListUrl,sendData:self.sendData});
			self.mask.hide();
			self.main.removeClass('active');
			$targetSelector.hide();
			parentContainer.find('.open').hide().removeClass('open');
			e.preventDefault();
			return false;
		});
	},
	/*户型模块进行操作*/
	checkBoxes:function(options){
		var self=this;
		var targetSelector=$(options.targetSelector);
		var $inputHidden=$(options.inputHidden);
		var title=options.title;
		var	parentContainer=self.searchFilter;
		targetSelector.off('tap','li').on('tap','li',function(e){
			var $this=$(this);
			if($this.hasClass('no-icon')){
				/*点击不限清空*/
				$this.siblings().removeClass('chosen');
				/*添加隐藏域*/
				$inputHidden.val($this.attr('data-value'));
            	self.requestData({url:self.getRewardListUrl,sendData:self.sendData});

				self.typeList.find('.on').children('span').html(title).removeClass('selected').end().removeClass('on');
				parentContainer.find('.open').hide().removeClass('open');
				targetSelector.hide();
				self.mask.hide();
				self.main.removeClass('active');
			}else if($this.hasClass('input-price')){
				// console.log(arrInput)
			}else{
				$this.hasClass('chosen')?$this.removeClass('chosen'):$this.addClass('chosen');
			}
			e.preventDefault();
			return false;
		});
		
	},
	/*点击确定按钮添加隐藏域*/
	searchBtn:function(options){
		var self=this;
		var targetSelector=$(options.targetSelector);
		var inputHidden=$(options.inputHidden);
		var parentContainer=self.searchFilter;
		var title=options.title;
		var $input=$(options.input);
		/*输入价格获取焦点清空checked*/
		$input.focus(function(e){
			var $this=$(this);
			$this.parent().parent().siblings().removeClass('chosen');
		});
		targetSelector.children('p').off('tap').on('tap',function(e){
			var arrOli=[];
			var dataList= targetSelector.find('.chosen');
			if(dataList&&dataList.length!=0){
				$.each(dataList,function(idx,ele){
					arrOli.push($(ele).attr('data-value'));
				});
				if(arrOli.length>1){
					self.typeList.find('.on').children('span').html('多选').addClass('selected').end().removeClass('on');
				}else if(arrOli.length===0){
					self.typeList.find('.on').children('span').html(title).removeClass('selected').end().removeClass('on');
				}else if(arrOli.length===1){
					self.typeList.find('.on').children('span').html(dataList.html()).addClass('selected').end().removeClass('on');
				}
				inputHidden.val(arrOli.join("-"));
			}else{
				var val1=$input.eq(0).val();
				var val2=$input.eq(1).val();
				if(val1&&!!!val2){
					/*添加隐藏域*/
					inputHidden.val(val1+'|1000000');
					self.typeList.find('.on').children('span').html(val1+"万以上").addClass('selected').end().removeClass('on');
				}else if(!!!val1&&val2){
					/*添加隐藏域*/
					inputHidden.val('0|'+val2);
					self.typeList.find('.on').children('span').html(val2+"万以下").addClass('selected').end().removeClass('on');
				}else if(val1&&val2){
					inputHidden.val(val1+'|'+val2);
					self.typeList.find('.on').children('span').html(val1+'-'+val2+"万").addClass('selected').end().removeClass('on');
				}else{
					self.typeList.find('.on').children('span').html(title).removeClass('selected').end().removeClass('on');
					inputHidden.val("")
				}
			};
            self.requestData({url:self.getRewardListUrl,sendData:self.sendData});
			targetSelector.hide();
			parentContainer.find('.open').hide().removeClass('open');
			self.main.removeClass('active');
			self.mask.hide();
			e.preventDefault();
			return false;
		})
	},
	/*点击蒙版的时候让div消失，若是没有点击确定并清楚对应的样式*/
	onClickMask:function(options){
		var self=this;
		var targetSelector=$(options.targetSelector);
		var typeList=self.typeList;
		var parentContainer=self.searchFilter;
		var arrLsit=[];
		targetSelector.off('tap').on('tap',function(e){
			var $this=$(this);
			var checked=parentContainer.find('.open').find('li');
			var spanInnerHTML=typeList.find('.on').children('span').html();
			if(spanInnerHTML==="总价"||spanInnerHTML==="户型"||spanInnerHTML==="更多"||spanInnerHTML==="区域/模块"){
				$(checked).removeClass('chosen');
			};
			parentContainer.find('.open').hide().removeClass('open');
			typeList.find('.on').removeClass('on');
			self.main.removeClass('active');
			$this.hide();
			e.preventDefault();
			return false;
		});
	},
	/*请求数据*/
    requestInitData:function(options) {
        var url=options.url;
        var sendData=options.sendData;
        var callBack=options.callBack;
        $.ajax({
            data:sendData,
            type: "POST",
            contentType: "application/x-www-form-urlencoded;charset=utf-8",
            dataType:"json",
            url:url,
            crossDomain:true,
            success:function(data){
                if(typeof data==="string"){
                    data=JSON.parse(data);
                }
                if(data.code==101 ||data.code==102){
                    console.log("token为空或者token失效");
                    window.location.href='login.html';
                };
                callBack(data);
            },
            timeout:10000,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                common.errDialog("网络不畅，请稍后重试");  
            }
        });
    },
    /*请求数据*/
    requestData:function(options) {
    	var self=this;
        var url=options.url;
        var sendData=options.sendData;
        var formData=common.getSendDataByForm(self.myForm);
            sendData = $.extend({}, sendData, formData); 
           	self.houseSaleListPanel.html("");
        $.ajax({
            data:sendData,
            type: "POST",
            contentType: "application/x-www-form-urlencoded;charset=utf-8",
            dataType:"json",
            url:url,
            crossDomain:true,
            success:function(data){
                if(typeof data==="string"){
                    data=JSON.parse(data);
                }
                if(data.code==101 ||data.code==102){
                    console.log("token为空或者token失效");
                    window.location.href='login.html';
                };
                self.resMsg.text("").hide();
                self.loadingFail.hide();
                if(!!data && data['code']=="0"){
                    var totalNum=data.res.data.page.recordCount;
                    if(totalNum==0){
                        self.loadingFail.show();
                    }else{
                        data=data.res.data.record;
                        if(!data.length){
                            self.resMsg.text("已经没有更多信息了").show();
                            self.flag=false;
                        }else{
                            var responseDom=self.buildListDomOfDataList({
                                loadingSelector:self.resMsg,
                                imgBasePath:self.imageHost,
                                pageTargetType:"_self",
                                dataList:data
                            });
                            self.houseSaleListPanel.append(responseDom);
                            self.flag=true;
                        };
                    };
                };
            },
            timeout:10000,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                common.errDialog("网络不畅，请稍后重试");  
            }
        });
    },
    /*点击区域或者地铁，第一级列表*/
    _pressZoneOrStation:function(){
    	var self=this;
    	self.firstList.off('tap','li').on('tap','li',function(e){
            var $this=$(this);
            $this.hasClass('chosen')?"":$this.addClass('chosen').siblings().removeClass('chosen')&&self.panelCell.css({'width':'50%'})&&self.thridList.parent().hide();
            $this.parent().parent().attr('data-value',$this.attr('data-value'));
            var linesList=[];
            var initOli='<li class="chosen">不限</li>';
            linesList.push(initOli);
            if(self.firstList.attr('data-value')==="subway"){
                var dataLineList=self.lineList.sort(function (a,b) {
                    return a["sort"]-b["sort"];
                });
                $.each(dataLineList,function (idx, ele) {
                    linesList.push('<li data-value="'+ele.id+'">'+ele.lineName+'</li>');
                });
                /*点击区域或者地铁线*/
				self._pressLineOrArea({dataList:dataLineList,selectedType:"subway"});
            }else if(self.firstList.attr('data-value')==="district"){
                var dataZoneList=self.zoneList;
                 $.each(dataZoneList,function (idx, ele) {
                    linesList.push('<li data-value="'+ele.id+'">'+ele.zoneName+'</li>');
                });
                /*点击区域或者地铁线*/
				self._pressLineOrArea({dataList:dataZoneList,selectedType:"district"});
            }
            self.secondList.html(linesList.join(""));
            e.preventDefault();
            return false;
        });
    },
    /*选择地铁线或者区域，第二级列表*/
    _pressLineOrArea:function(options){
    	var self=this;
    	var dataList=options.dataList;
    	var selectedType=options.selectedType;
        self.secondList.off('tap','li').on('tap','li',function(e){
            var $this=$(this);
            var linesList=[];
            var initOli='<li class="chosen">不限</li>';
                linesList.push(initOli);
            $this.hasClass('chosen')?"":$this.addClass('chosen').siblings().removeClass('chosen');
            self.thridList.parent().show().attr({'data-value':""});
            var selfIndex=$this.index()-1;
            if(selfIndex===-1){
            	$this.parent().parent().attr('data-value',"")&&self.panelCell.css({'width':'50%'})&&self.thridList.parent().hide();	
            	self._controlMaskAndTypeList({content:'地铁/区域'});
            	self.main.removeClass('active');
            	self._addInputHidden({
	            	lineId:self.lineId,
	            	stationId:self.stationId,
	            	zoneId3:self.zoneId3,
	            	zoneId4:zoneId4,
	            });
            	self.requestData({url:self.getRewardListUrl,sendData:self.sendData});
            }else{
            	$this.parent().parent().attr('data-value',$this.attr('data-value'))&&self.panelCell.css({'width':'33.3%'});
            	if(selectedType==="subway"){
	            	var dataSubwayList=dataList[selfIndex]['stations'].sort(function (a, b) {
	                    return a['sort']-b['sort'];
	                });
	                $.each(dataSubwayList,function (idx, itm) {
		                linesList.push('<li data-value="'+itm.stationId+'">'+itm['stationName']+'</li>');
		            });
	            }else if(selectedType==="district"){
	            	var dataDistrictList=dataList[selfIndex]["subZone"];
	            	$.each(dataDistrictList,function (idx, itm) {
		                linesList.push('<li data-value="'+itm.id+'">'+itm['zoneName']+'</li>');
		            });
	            }
	            self._addInputHidden({
	            	lineId:self.lineId,
	            	stationId:self.stationId,
	            	zoneId3:self.zoneId3,
	            	zoneId4:zoneId4,
	            });
            };
            self.thridList.html(linesList.join(""));
            e.preventDefault();
            return false;
        });
    },
    /*选择第三级列表*/
  	_pressPositionList:function(){
  		var self=this;
  		self.thridList.off('tap','li').on('tap','li',function(e){
            var $this=$(this);
            $this.hasClass('chosen')?"":$this.addClass('chosen').siblings().removeClass('chosen');
            $this.parent().parent().attr('data-value',$this.attr('data-value'));
            var typeListHtml=$(self.secondList.find('.chosen'));
            var thirdIndex=$this.index();
            thirdIndex===0? $this.parent().parent().attr('data-value',"")&&self._controlMaskAndTypeListAddClassSelected({content:typeListHtml.html()}):$this.parent().parent().attr('data-value',$this.attr('data-value'))&&self._controlMaskAndTypeListAddClassSelected({content:$this.html()});
            self._addInputHidden({
            	lineId:self.lineId,
            	stationId:self.stationId,
            	zoneId3:self.zoneId3,
            	zoneId4:zoneId4,
            });
			self.main.removeClass('active');
            self.requestData({url:self.getRewardListUrl,sendData:self.sendData});
            e.preventDefault();
            return false;
        });
  	},
  	/*open用于标识显示的模块，移除open类*/
  	_controlMaskAndTypeList:function(options){
  		var self=this;
  		var content=options.content;
  		self.searchFilter.find('.open').hide().removeClass('open');//控制显示的模块消失
        self.typeList.find('.on').children('span').html(content).removeClass('selected').end().removeClass('on');//去除头部显示的样式
        self.mask.hide();//控制蒙版消失
		self.main.removeClass('active');
  	},
  	_controlMaskAndTypeListAddClassSelected:function(options){
  		var self=this;
  		var content=options.content;
  		self.searchFilter.find('.open').hide().removeClass('open');//控制显示的模块消失
        self.typeList.find('.on').children('span').html(content).addClass('selected').end().removeClass('on');//去除头部显示的样式
        self.mask.hide();//控制蒙版消失
		self.main.removeClass('active');
  	},
  	/*区域和地铁添加隐藏域*/
  	_addInputHidden:function(options){
  		var self=this;
  		var $lineId=$(options.lineId);
  		var $stationId=$(options.stationId);
  		var $zoneId3=$(options.zoneId3);
  		var $zoneId4=$(options.zoneId4);
  		var $secondListParent=$(self.secondList.parent());
  		var $thridListParent=$(self.thridList.parent());
  		if(self.firstList.attr('data-value')==='district'){
  			$lineId.val("");
  			$stationId.val("");
  			$zoneId3.val($secondListParent.attr('data-value'));
  			$zoneId4.val($thridListParent.attr('data-value'));
  		}else if(self.firstList.attr('data-value')==='subway'){
  			$zoneId3.val("");
  			$zoneId4.val("");
  			$lineId.val($secondListParent.attr('data-value'));
  			$stationId.val($thridListParent.attr('data-value'));
  		}
  	},
  	buildListDomOfDataList:function(options) {
        var dataList=options.dataList||[];
        var imgBasePath=options.imgBasePath||"./";
        var pageTargetType=options.pageTargetType||"_blank";
        var $loading=$(options.loadingSelector);
        var arrTemp=[];
        var dataCount=0;
        $.each(dataList,function (idx, obj) {
            dataCount++;
            var hoseTypeText="";
            hoseTypeText+=obj['houseTypeOne']===""?"":obj['houseTypeOne']+"室";
            hoseTypeText+=obj['houseTypeTwo']===""?"&nbsp;":obj['houseTypeTwo']+"厅&nbsp;";
            var houseAreaText=obj['houseFloorArea']===""?"":obj['houseFloorArea']+"m²&nbsp;&nbsp;";//建筑面积
            var orientation=obj['houseOrientations']?obj['houseOrientations']:"";//朝向
            var typicalDom=houseAreaText+hoseTypeText+orientation;
            var isRecommended=obj['isRecommended']?obj['isRecommended']:"";
            var isNew=obj['isNew']?obj['isNew']:"";
            isRecommended=isRecommended=="1"?'<li class="esheyi-recommended">舍艺推荐</li>':"";
            isNew=isNew=="1"?'<li class="recently-added">最近新增</li>':"";
            var rewardTitle=obj['rewardTitle']?obj['rewardTitle']:"";
            var isVisited=obj['isVisited']==0?'<i class="firstTime"></i>':'';//判断是否是首次带看的房源；
            var listingPriceDom=obj['quotePrice']===""? "" : '<i>'+obj['quotePrice']+'万</i>';
            var unitPriceDom=obj['unitPrice']===""?"" : '<span class="unit-price">'+obj['unitPrice']+'元/m²</span>';
            var addressDom=obj['villageName']?'<span class="address">'+obj['villageName']+'</span>':"";
            var tempDom='<li class="panel">'+
                                '<a href=./houseDetail.html?id='+obj['rewardId']+' target='+pageTargetType+'>'+
                                    '<div class="cover-image"><img src="'+imgBasePath+obj['coverPhoto']+'"></div>'+
                                    '<div class="house-info">'+
                                        '<h5>'+isVisited+'<i></i>'+rewardTitle+'</h5>'+
                                        '<div class="clearfix">'+typicalDom+listingPriceDom+'</div>'+
                                        '<p class="clearfix">'+addressDom+unitPriceDom+'</p>'+
                                        '<ul class="features clearfix">'+isRecommended+isNew+'</ul>'+
                                    '</div>'+
                                '</a>'+
                            '</li>';
            arrTemp.push(tempDom) ;
        });
        $loading.length>0?(dataList.length && dataList.length<10 || dataCount<10 ? $loading.text("已经没有更多信息了").show():$loading.text("").hide()):"无点击加载选择器";
        return arrTemp.join("");
    },
};
window.SortForm = new SortFormObject();